package com.hui.security.sys.service.impl;

import com.hui.security.sys.entity.Role;
import com.hui.security.sys.exception.ExceptionEnum;
import com.hui.security.sys.exception.RoleException;
import com.hui.security.sys.mapper.RoleMapper;
import com.hui.security.sys.service.RoleService;
import com.hui.security.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
/**
 * <b><code>RoleServiceImpl</code></b>
 * <p/>
 * Description:
 * <p/>
 * <b>Creation Time:</b> 2019/1/5 0:27.
 *
 * @author HuWeihui
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserService userService;
    /**
     * 新增角色
     *
     * @param role
     * @return
     */
    @Override
    public Role add(Role role) {
        //判断是否有重复角色
        if (null != roleMapper.selectByRoleName(role.getRoleName())){
            throw new RoleException(ExceptionEnum.ROLE_ERROR_REPEAT_ROLE);
        }
        roleMapper.insertSelective(role);
        return role;
    }

    /**
     * 删除角色
     *
     * @param roleId
     */
    @Override
    public void delete(String roleId) {
        roleMapper.deleteByPrimaryKey(roleId);
    }

    /**
     * 更新角色
     *
     * @param role
     */
    @Override
    public void update(Role role) {
        //判断是否有重复角色
        if (null != roleMapper.selectByRoleName(role.getRoleName())){
            throw new RoleException(ExceptionEnum.ROLE_ERROR_REPEAT_ROLE);
        }
        roleMapper.updateByPrimaryKey(role);
    }

    /**
     * 查询角色
     *
     * @param roleId
     * @return
     */
    @Override
    public Role get(String roleId) {
        return roleMapper.selectByPrimaryKey(roleId);
    }

    /**
     * 删除用户相关角色
     *
     * @param userId
     */
    @Override
    public void deleteByUserId(String userId) {
        roleMapper.deleteRefByUserId(userId);
        //删除角色相关用户关联
        userService.deleteRefByRoleId(userId);
        //删除角色相关的权限关联

    }

    /**
     * 查询用户相关角色
     *
     * @param userId
     * @return
     */
    @Override
    public List<Role> listByUserId(String userId) {
        return roleMapper.selectByUserId(userId);
    }
}
